package it.uniroma3.dia.accesso;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import winterwell.jtwitter.Twitter;

/*Contiene un oggetto twitter per l'interfacciamento con le api Twitter e gestisce la scadenza
 * delle richieste. Sovrascrive i metodi Twitter.getUser(), Twitter.gertFriends(), Twitter.getUserTimeline()
 */
public class TwitterWrapper extends Twitter{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private Twitter twitter;

	
	public TwitterWrapper(Twitter twitter) {
		this.twitter = twitter;
	}

	public User getUser(String utente) {
		User user = null;
		try{
			user = twitter.getUser(utente);
		}catch (Exception ex) {
			if (ex.getMessage().contains("401 Unauthorized") || ex.getMessage().contains("404 Error")) {
				System.out.println("401/404 ignored");

			} else {

				System.out.println("Error / Rate limit reached, sleeping for pre-set time." + new Date() + " "
						+ ex.getMessage());
				try {
					Thread.sleep(1000 * 60 * 25);
					return getUser(utente);
				} catch (InterruptedException e) {
					throw new RuntimeException(e);
				}
			}
		}
		return user;
	}

	public List<User> getFriends(String username) {
		List<User> amici = new LinkedList<User>();
		try{
			amici = twitter.getFriends(username);
		}catch (Exception ex) {
			if (ex.getMessage().contains("401 Unauthorized") || ex.getMessage().contains("404 Error")) {
				System.out.println("401/404 ignored");

			} else {

				System.out.println("Error / Rate limit reached, sleeping for pre-set time." + new Date() + " "
						+ ex.getMessage());
				try {
					Thread.sleep(1000 * 60 * 25);
					return getFriends(username);
				} catch (InterruptedException e) {
					throw new RuntimeException(e);
				}
			}
		}
		return amici;
	}

	public List<Status> getUserTimeline(String username) {
		List<Status> st = new LinkedList<Status>();
		try{
			st = twitter.getUserTimeline(username);
		}catch (Exception ex) {
			if (ex.getMessage().contains("401 Unauthorized") || ex.getMessage().contains("404 Error")) {
				System.out.println("401/404 ignored");

			} else {

				System.out.println("Error / Rate limit reached, sleeping for pre-set time." + new Date() + " "
						+ ex.getMessage());
				try {
					Thread.sleep(1000 * 60 * 25);
					return getUserTimeline(username);
				} catch (InterruptedException e) {
					throw new RuntimeException(e);
				}
			}
		}
		return st;
	}

}
